package com.example.administrator.nl.activity.register;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.Layout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.administrator.nl.MainActivity;
import com.example.administrator.nl.R;
import com.example.administrator.nl.activity.LoginActivity;
import com.example.administrator.nl.base.BaseActivity;
import com.example.administrator.nl.dialog.DialogCameraRollView;
import com.example.administrator.nl.util.ToastUtil;
import com.leaf.library.StatusBarUtil;
import com.nanchen.compresshelper.CompressHelper;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class RegisterBusinessOrPartnerActivity extends BaseActivity {
    // 注册类型
    @BindView(R.id.tv_title_register)
    TextView tv_title_register;

    @BindView(R.id.rl)
    RelativeLayout rl;

    // 返回键
    @BindView(R.id.iv_finish)
    ImageView iv_finish;

    // 页面标题
    @BindView(R.id.tv_title)
    TextView tv_title;

    // 拍摄营业执照
    @BindView(R.id.iv_license)
    ImageView iv_license;

    // 拍摄营业执照
    @BindView(R.id.ll_camera_register)
    LinearLayout ll_camera_register;

    // 立即注册按钮
    @BindView(R.id.tv_register_business)
    TextView tv_register_business;

    // 公司名
    @BindView(R.id.et_company_name_register_business)
    EditText et_company_name_register_business;

    // 公司地址
    @BindView(R.id.et_company_address_register_business)
    EditText et_company_address_register_business;

    // 联系人
    @BindView(R.id.et_company_contacts_register_business)
    EditText et_company_contacts_register_business;

    // 手机号
    @BindView(R.id.et_phone_register_business)
    EditText et_phone_register_business;

    // 验证码
    @BindView(R.id.et_verification_code_register_business)
    EditText et_verification_code_register_business;

    @BindView(R.id.check_agree_register_business)
    CheckBox check_agree_register_business;

    // 选择相机还是相册提示框
    private DialogCameraRollView dialogCameraRollView;
    private static final int REQUEST_TAKE_PHOTO_CODE = 101;

    // 储存照片UTL
    Uri storageImageUrl;
    // 储存图片
    File storageImageFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listener();

    }


    @Override
    public int getContentView() {
        return R.layout.activity_register_business_or_partner;
    }

    @Override
    public void init() {
        StatusBarUtil.setGradientColor(this, rl);
        String registerType = getIntent().getStringExtra("type");
        if (!TextUtils.isEmpty(registerType)) {
            if ("1".equals(registerType)) {
                tv_title_register.setText("成为店家，只需三步");
                tv_title.setText("店家申请");

            } else if ("2".equals(registerType)) {
                tv_title_register.setText("成为合伙人，只需三步");
                tv_title.setText("合伙人申请");
            }
        }
    }


    private void listener() {
        ll_camera_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogCameraRollView.show();
            }
        });
        dialogCameraRollView = new DialogCameraRollView(this, R.layout.dialog_camera_roll_layout, new int[]{R.id.tv_camera_view, R.id.tv_album_view, R.id.tv_cancel_view});
        dialogCameraRollView.setOnCenterItemClickListener(new DialogCameraRollView.OnCenterItemClickListener() {
            @Override
            public void OnCenterItemClick(DialogCameraRollView dialog, View view) {
                switch (view.getId()) {
                    case R.id.tv_camera_view:
                        ToastUtil.ToastShort("打开相机");
                        takePhoto();
                        dialog.dismiss();
                        break;
                    case R.id.tv_album_view:
                        ToastUtil.ToastShort("打开相册");
                        photo();
                        dialog.dismiss();
                        break;
                    case R.id.tv_cancel_view:
                        ToastUtil.ToastShort("关闭弹窗");

                        dialog.dismiss();
                        break;
                }
            }
        });

        // 立即注册成为店家或者合伙人
        tv_register_business.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
            }
        });
    }

    private void register() {
        if (!TextUtils.isEmpty(et_company_name_register_business.getText())) {
            if (!TextUtils.isEmpty(et_company_address_register_business.getText())) {
                if (!TextUtils.isEmpty(et_company_contacts_register_business.getText())) {
                    if (!TextUtils.isEmpty(et_phone_register_business.getText())) {
                        if (!TextUtils.isEmpty(et_verification_code_register_business.getText())) {
                            if (isImage) {
                                if (check_agree_register_business.isChecked()) {
                                    Intent intent = new Intent(RegisterBusinessOrPartnerActivity.this, LoginActivity.class);
                                    intent.putExtra("phone","");
                                    startActivity(intent);
                                    finish();
                                } else {
                                    ToastUtil.ToastShort("你还没有同意协议");
                                }
                            } else {
                                ToastUtil.ToastShort("营业执照不能为空");
                            }
                        } else {
                            ToastUtil.ToastShort("验证码不能为空");
                        }
                    } else {
                        ToastUtil.ToastShort("手机号不能为空");
                    }
                } else {
                    ToastUtil.ToastShort("联系人不能为空");
                }
            } else {
                ToastUtil.ToastShort("地址不能为空");
            }
        } else {
            ToastUtil.ToastShort("公司名不能为空");
        }
    }


    // 打开相机
    private void takePhoto() {
        // 创建存储照片的文件
        storageImageFile = new File(Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis() + ".jpg");

        // 判断文件是否存在，不存在就创建
        if (!storageImageFile.getParentFile().exists()) {
            storageImageFile.getParentFile().mkdirs();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // android7.0及以上获取文件url
            String authority = getPackageName() + ".provider";
            storageImageUrl = FileProvider.getUriForFile(RegisterBusinessOrPartnerActivity.this, authority, storageImageFile);
        } else {
            storageImageUrl = Uri.fromFile(storageImageFile);
        }
        // 调取系统拍照
        //步骤四：调取系统拍照
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, storageImageUrl);
        startActivityForResult(intent, REQUEST_TAKE_PHOTO_CODE);
    }

    ArrayList<AlbumFile> mSelectedAlbumFiles;

    public void photo() {
        Album.image(this)
                .multipleChoice()
                .camera(true)
                // 每行显示3个
                .columnCount(3)
                // 选中一个
                .selectCount(1)
                .checkedList(mSelectedAlbumFiles)
                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @SuppressLint("CheckResult")
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {
                        mSelectedAlbumFiles = result;
                        List<File> files = new ArrayList<>();

                        for (int i = 0; i < result.size(); i++) {
                            // 压缩图片
                            files.add(compressPhoto(result.get(i).getPath()));

                        }
                        Glide.with(RegisterBusinessOrPartnerActivity.this).load(files.get(0)).into(iv_license);
                        isImage = true;

                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                    }
                })
                .start();
    }

    boolean isImage = false;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String photoPath;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            photoPath = String.valueOf(storageImageFile);
        } else {
            photoPath = storageImageUrl.getEncodedPath();
        }
        Log.d("拍照返回图片路径:", photoPath);
        Glide.with(RegisterBusinessOrPartnerActivity.this).load(photoPath).into(iv_license);
        isImage = true;
    }

    private File compressPhoto(String fileUrl) {
        // 默认最大宽度为720
        int maxWidth = 720;
        // 默认最大高度为960
        int maxHeight = 960;
        // 默认压缩质量为80
        int quality = 80;

        File newFile = new CompressHelper.Builder(getApplicationContext())
                .setMaxWidth(maxWidth)
                .setMaxHeight(maxHeight)
                .setQuality(quality)
                // 设置你需要修改的文件名
                .setFileName(System.currentTimeMillis() + "")
                // 设置默认压缩为jpg格式
                .setCompressFormat(Bitmap.CompressFormat.JPEG)
                .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES).getAbsolutePath())
                .build()
                .compressToFile(new File(fileUrl));
        return newFile;
    }
}
